<template>
  <div id="comments" style="background-color: #f7f7f7">
    <nav-bar title="订单评论"/>
    <div class="comment-container" v-if="commentsForm && commentsForm.comments">
      <div class="cm-item" v-for="(cm, index) in commentsForm.comments" :key="index">
        <div class="cm-nav" v-if="isFirstComment">
          <img :src="skulist[index].goods_image" :alt="skulist[index].name" class="cm-img"/>
          <div class="cm-grade">
            <span class="item-flower praise" :class="[cm.grade === 'good' && 'active']">
              <input type="radio" v-model="cm.grade" value="good">
              <i></i>
              <span>好评</span>
            </span>
            <span class="item-flower average" :class="[cm.grade === 'neutral' && 'active']">
              <input type="radio" v-model="cm.grade" value="neutral">
              <i></i>
              <span>中评</span>
            </span>
            <span class="item-flower bad-review" :class="[cm.grade === 'bad' && 'active']">
              <input type="radio" v-model="cm.grade" value="bad">
              <i></i>
              <span>差评</span>
            </span>
          </div>
        </div>
        <div class="acm-nav" v-else>
          <div><img :src="goodsCommentsInfo[index].goods_img" :alt="goodsCommentsInfo[index].goods_name" class="cm-img"/></div>
          <ul class="comments_score">
            <template v-if="cm.$$goods_comment">
              <li>初评日期：{{cm.$$goods_comment.create_time | unixToDate }}</li>
              <li>初评评分：{{cm.$$goods_comment.grade === 'good' ? '好评' : cm.$$goods_comment.grade === 'neutral' ? '中评' : cm.$$goods_comment.grade === 'bad' ? '差评': ''}}</li>
              <li style="overflow: hidden;word-wrap: break-word;">初评内容：{{cm.$$goods_comment.content}}</li>
	            <li v-if="cm.$$goods_comment.images && cm.$$goods_comment.images.length">
		            <span class="comments-images-label">初评图片:</span>
                <van-image-preview
                  v-model="showPreImg"
                  :startPosition="indexes"
                  :images="cm.$$goods_comment.images"
                  @change="(index) => { indexes = index }"
                >
                  <template v-slot:index>第{{ indexes }}张</template>
                </van-image-preview>
                <img class="comments-images" v-for="(img, index) in cm.$$goods_comment.images" :src="img" :key="index" @click="showPreImg = true;indexes = index"/>
	            </li>
              <li>
                初评审核状态：
                <span v-if="cm.$$goods_comment.audit_status === 'WAIT_AUDIT'">您的初评待审核，不能进行追评</span>
                <span v-if="cm.$$goods_comment.audit_status === 'REFUSE_AUDIT'">您的初评审核未通过，不能进行追评</span>
                <span v-if="cm.$$goods_comment.audit_status === 'PASS_AUDIT'">您的初评审核通过</span>
              </li>
            </template>
          </ul>
        </div>
        <div class="cm-con" v-if="isFirstComment || cm.$$goods_comment.audit_status === 'PASS_AUDIT'">
          <van-field
            v-model="cm.content"
            type="textarea"
            :placeholder="cm.grade === 'good' ? '宝贝满足您的期待吗？说说它的优点和美中不足的地方吧' : '可以告诉我们您遇到了什么问题吗？'"
            :error-message="errorMsgs[index]"
            rows="4"
          />
        </div>
        <div class="cm-photo" v-if="isFirstComment || cm.$$goods_comment.audit_status === 'PASS_AUDIT'">
          <div class="cm-photos">
            <a href="javascript:;" v-for="(img, index) in cm.images" :key="index" class="img-item">
              <van-icon name="clear" @click="cm.images.splice(index, 1)"/>
              <img :src="img">
            </a>
          </div>
          <van-uploader v-if="cm.images.length < 5" :after-read="(file) => { onFileRead(cm, file) }" accept="image/png, image/jpeg, image/jpg">
            <van-icon name="photograph" />
          </van-uploader>
        </div>
      </div>
      <div class="shop-grade" v-if="isFirstComment">
        <div class="shop-grade-nav">
          <van-icon name="shop"/>店铺评分
        </div>
        <div class="rating-star">
          <div class="logistics-star">
            <div class="text">
              <span>描述相符</span>
            </div>
            <div class="star">
              <van-rate v-model="commentsForm.description_score" color="#f42424"/>
            </div>
            <div class="grade-text">
              <span>{{ countGradeText(commentsForm.description_score) }}</span>
            </div>
          </div>
          <div class="logistics-star">
            <div class="text">
              <span>服务态度</span>
            </div>
            <div class="star">
              <van-rate v-model="commentsForm.service_score" color="#f42424"/>
            </div>
            <div class="grade-text">
              <span>{{ countGradeText(commentsForm.service_score) }}</span>
            </div>
          </div>
          <div class="logistics-star">
            <div class="text">
              <span>物流服务</span>
            </div>
            <div class="star">
              <van-rate v-model="commentsForm.delivery_score" color="#f42424"/>
            </div>
            <div class="grade-text">
              <span>{{ countGradeText(commentsForm.delivery_score) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <van-button type="danger" v-if="button_show" :disabled="cantComments" size="large" @click="submitForm" class="cm-btn">发表评论</van-button>
  </div>
</template>

<script>
  import Vue from 'vue'
  import * as API_Order from '@/api/order'
  import * as API_Members from '@/api/members'
  import request, { Method } from '@/utils/request'
  import { ImagePreview } from 'vant'
  Vue.use(ImagePreview)
  import '../../static/lrz/lrz.all.bundle'
  export default {
    name: 'comments',
    head() {
      return {
        title: `评价商品-${this.site.title}`
      }
    },
    data() {
      return {
        order_sn: this.$route.query.order_sn,
        skulist: '',
        commentsForm: {},
        indexes: 0,
        /** 是否显示初评图片预览 */
        showPreImg: false,
        // 不能评论【已评论过】
        cantComments: false,
        // 是否为初评价 true 默认为初评
        isFirstComment: !this.$route.query.append_comment,
        // 错误信息
        errorMsgs: [],
        goodsCommentsInfo: {}
      }
    },
    computed: {
      button_show () {
        let { comments = [] } = this.commentsForm
        if (this.isFirstComment) return true
        return comments.some(item => item.$$goods_comment.audit_status === 'PASS_AUDIT')
      }
    },
    mounted() {
      let { append_comment, sku_id } = this.$route.query
      if (append_comment === 'review') this.isFirstComment = false
      let commentsResult
      /**获取订单详情**/
      API_Order.getOrderDetail(this.order_sn).then(async response => {
        this.skulist = commentsResult = response.order_sku_list
        if (append_comment === 'review') {
          this.goodsCommentsInfo = commentsResult = await API_Members.getGoodsFirstComments({ order_sn: this.order_sn, sku_id })
        }
        this.commentsForm = {
          order_sn: this.order_sn,
          delivery_score: 5,
          description_score: 5,
          service_score: 5,
          comments: commentsResult.map((item, index) => {
            this.errorMsgs[index] = ''
            return {
              $$goods_comment: item,
              sku_id: item.sku_id,
              content: '',
              grade: 'good',
              images: []
            }
          })
        }
      })
    },
    methods: {
      countGradeText(val) {
        switch (val) {
          case 5: return '非常好'
          case 4: return '好'
          case 3: return '一般'
          case 2: return '差'
          case 1: return '非常差'
          default: return '非常好'
        }
      },
      /** 图片上传 */
      onFileRead(cm, file) {
        lrz(file.file).then(async rst => {
          const res = await request({
            url: this.MixinUploadApi,
            method: Method.POST,
            headers: { 'Content-Type': 'multipart/form-data' },
            data: rst.formData
          })
          res && cm.images.push(res.url)
        })
      },
      submitForm() {
        const params = JSON.parse(JSON.stringify(this.commentsForm))
        params.comments.forEach(key => {
          // 如果没有评价 则默认好评
          if(!key.grade) key.grade = 'good'
	        // 如果是追评 && 没有评价id
          if(!this.isFirstComment && !key.comment_id) key.comment_id = key.$$goods_comment.comment_id
          // delete key.$$goods_comment
        })

	      // 初评校验 非好评 必须输入原因
        if(this.isFirstComment) {
          const result = params.comments.some(key => (key.grade !== 'good' && !key.content))
          if(result) {
            this.$message.error('请告诉我们您不满意的原因，我们愿尽最大的努力！');
            return false
          }
        }
        // 追评校验
        if(!this.isFirstComment) {
          params.comments = params.comments.filter(key => key.$$goods_comment.audit_status === 'PASS_AUDIT');
          params.comments.forEach(item => delete item.$$goods_comment)
          const result = params.comments.some(key => !key.content);
          if(result) {
            this.$message.error('请填写追评内容！');
            return false
          }
        }
        API_Members[!this.isFirstComment?'AppendCommentsOrder':'commentsOrder'](!this.isFirstComment?params.comments:params).then(() => {
          this.$message.success('发表成功')
          this.$router.replace({ path: '/member/my-comments?order_status=WAIT_COMMENT' })
        })
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  .comment-container {
    padding-top: 46px;
    padding-bottom: 50px;
  }
  .cm-btn {
    position: fixed;
    bottom: 0;
    border-radius: 0;
  }
  .cm-item {
    width: 100%;
    background: white;
    margin-bottom: 15px;
  }
  .acm-nav{
    border-bottom: 1px solid #e4e2e2;
    padding-bottom:5px;
    .comments_score{
      padding-left: 10px;
    }
  }
  .cm-nav {
    display: flex;
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #e4e2e2;
  }
  .cm-img {
    height: 40px;
    width: 40px;
    margin: 5px 5px 5px 10px;
  }
  .cm-grade {
    display: flex;
    width: calc(100% - 85px);
    margin-left: 30px;
    .item-flower {
      display: flex;
      align-items: center;
      width: 80px;
      height: 50px;
      position: relative;
      input {
        position: absolute;
        width: 100%;
        height: 100%;
        opacity: 0;
      }
      i {
        display: inline-block;
        width: 23px;
        height: 25px;
        margin-right: 5px;
      }
      &.praise i {
        background: url("") no-repeat center;
        background-size: 100%;
      }
      &.praise.active i {
        background: url("") no-repeat center;
        background-size: 100%;
      }
      &.average i, &.bad-review i {
        background: url("") no-repeat center;
        background-size: 100%;
      }
      &.average.active i, &.bad-review.active i {
        background: url("") no-repeat center;
        background-size: 100%;
      }
    }
  }
  .cm-con {
    textarea {
      resize: none;
      height: 100px;
      width: 100%;
      padding: 6px;
      background-color: #fff;
      border: none;
      box-sizing: border-box;
      overflow: hidden;
      font-size: 13px;
    }
  }
  .shop-grade {
    background-color: #fff;
    .shop-grade-nav {
      display: flex;
      align-items: center;
      height: 45px;
      line-height: 45px;
      position: relative;
      font-size: 14px;
      .van-icon {
        font-size: 24px;
        margin: 0 5px;
      }
    }
  }
  .rating-star {
    .logistics-star {
      height: 35px;
      line-height: 35px;
      clear: both;
      .text {
        float: left;
        font-size: 12px;
        margin-left: 6%;
        margin-right: 10px;
        color: #999;
        line-height: 30px;
      }
      .star {
        float: left;
      }
      .grade-text {
        float: left;
        font-size: 12px;
        color: #999;
        margin-left: 10px;
        line-height: 30px;
      }
    }
  }
  span.comments-images-label {
	  float: left;
  }
  .comments-images {
	  width: 50px;
	  height: 50px;
	  margin-left: 5px;
	  object-fit: contain;
  }
  .cm-photo {
    padding: 5px 10px;
    border-top: 1px solid #e4e2e2;
    /deep/ .van-icon {
      font-size: 28px;
    }
  }
  .cm-photos {
    display: flex;
    align-items: center;
    .img-item {
      position: relative;
      /deep/ .van-icon {
        position: absolute;
        top: 0;
        right: 0;
        color: red;
        font-size: 20px;
        background-color: #fff;
        border-radius: 100%;
        overflow: hidden;
      }
    }
    img {
      width: 50px;
      height: 50px;
      margin-right: 5px;
    }
  }
</style>
